<template>
    <view class="content" :data-theme="themeStore.theme">
        <eui-nav-bar title="更新日志" rightIcon="none" backgroundColor="#FFFFFF" color="#000000" statusBar="false"/>

        <scroll-view class="scroll-view" scroll-y :style="{height: scrollHeight + 'px'}">
            <eui-card hPadding="28" vPadding="28">
                <view class="flex-row" style="margin-bottom: 10px;">
                    <image src="../../../static/img/logo.png" alt="" class="img"/>
                    <view class="flex_1 right-box flex-column-between">
                        <view class="title">{{LogData.c_type}}{{LogData.c_version}}主要更新</view>
                        <view class="time text-color-auxiliary">{{LogData.c_create_dt}}</view>
                    </view>
                </view>
                <!-- 请勿格式化换行, pre会保留空格和换行符 -->
                <pre><textarea v-model="LogData.c_describe" disabled auto-height class="textarea"/></pre>
            </eui-card>
        </scroll-view>
        <view class="fixed_bottom" v-if="UpdateShow">
            <view class="notice-bar-row" >
                <eui-notice-bar
                    showIcon
                    text="注:因苹果限制,若重启后出现白屏，请手工关闭应用并重新打开即可!" 
                    backgroundColor="rgba(255, 97, 0, 0.1)" 
                    color="#FF6100"
                    class="notification-box"
                ></eui-notice-bar>
            </view>
            <view class="bottom-box">
                <eui-button type="primary" @click="onUpdate" title="立即更新" class="login-btn"/>
            </view>
        </view>
    </view>

</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useThemeStore } from '@/store/themeStore';
import { useSystemInfoStore } from '@/store/useSystemInfo';
const themeStore = useThemeStore(); // 主题
const systemInfo= useSystemInfoStore(); // 系统参数
const scrollHeight = ref<number>(400);
const downloadUrl = ref('');
const LogData = ref({});
const UpdateShow = ref(true);

// 初始化滚动区域高度
const initScrollView =() => {
    const screenWidth = systemInfo.systemInfo.screenWidth;
    const _height = UpdateShow.value ? ((250 / 750) * screenWidth) : 0; // 底部规定区域高度
    scrollHeight.value = systemInfo.usableScreenHeight - systemInfo.navBarHeight - _height;
}

onLoad((options) => {
    const { data, isUpdate } = options;
   
    const decodedData = decodeURIComponent(data);
    LogData.value = JSON.parse(decodedData)[0];
    downloadUrl.value = LogData.value.c_download_url;
    UpdateShow.value = isUpdate === 'true' ? true : false;
    initScrollView();
})


const onUpdate = () => {
    console.log('点击更新');
    const systemInfo = uni.getSystemInfoSync();
    const osName = systemInfo.platform;
    const base = { 
        filename: "_doc/update/"
    };
    if (downloadUrl.value.slice(0, 3) == "apk" && osName == "Android") {
        uni.showModal({
            title: '升级啦',
            content: '有新版本喽，现在下载吧？！管理后台已经更新，若不更新，暂时无法使用哦！',
            showCancel: true,
            success: (res) => {
                if (res.confirm) {
                    try {
                        plus.runtime.openURL(downloadUrl.value.slice(4, downloadUrl.value.length - 4));
                        setTimeout(function() {
                            // var cur = plus.webview.currentWebview();
                            // cur.close();
                            plus.runtime.quit();
                        }, 1000)
                    } catch (e) {
                        uni.showToast({
                            duration: 3500,
                            icon: 'none',
                            title: '打开更新包下载地址失败了！',
                            mask: true,
                        });
                        setTimeout(function() {
                            plus.runtime.quit();
                        }, 1000)
                    }
                }
            }
        });

    } else if (downloadUrl.value.slice(0, 3) == "ipa" && osName == "iOS") {
        uni.showModal({
            title: '升级啦',
            content: '有新版本喽，但需跳转至苹果商店进行更新，现在下载吧？！管理后台已经更新，若不更新，暂时无法使用哦！',
            showCancel: true,
            success: (res) => {
                if (res.confirm) {
                    try {
                        plus.runtime.openURL(downloadUrl.value.slice(4, downloadUrl.value.length - 4));
                        setTimeout(function() {
                            plus.runtime.quit();
                        }, 1000)
                    } catch (e) {
                        uni.showToast({
                            duration: 3500,
                            icon: 'none',
                            title: '打开更新包下载地址失败了！',
                            mask: true,
                        });
                    }
                }
            }
        });
    } else {
        var dtask = plus.downloader.createDownload(downloadUrl.value, base, function(d, status) {
            uni.showToast({
                title: '下载完成',
                mask: false,
                duration: 1000
            });
            // 下载完成
            if (status == 200) {
                plus.runtime.install(d.filename, {
                    force: false
                }, function() {
                    plus.nativeUI.closeWaiting();
                    uni.showModal({
                        title: '提示',
                        content: '更新成功！',
                        showCancel: false,
                        confirmText: '开始体验',
                        success: function(res) {
                            if (res.confirm) {
                                plus.runtime.restart();
                            }
                        }
                    });
                }, function(e) {
                    plus.nativeUI.closeWaiting();
                    uni.showModal({
                        title: '提示',
                        content: '更新失败，原因：' + e.message,
                        showCancel: false,
                        confirmText: '重新启动',
                        success: function(res) {
                            if (res.confirm) {
                                plus.runtime.restart();
                            }
                        }
                    });
                });
            } else {
                uni.showModal({
                    title: '提示',
                    content: '更新失败，请联系管理员！',
                    showCancel: false,
                    confirmText: '重新启动',
                    success: function(res) {
                        if (res.confirm) {
                            plus.runtime.restart();
                        }
                    }
                });
            }
        });
        try {
            dtask.start(); // 开启下载的任务
            var prg = 0;
            var showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象 
            dtask.addEventListener('statechanged', function(task,status) {
                // 给下载任务设置一个监听 并根据状态  做操作
                switch (task.state) {
                    case 1:
                        showLoading.setTitle("正在下载...");
                        break;
                    case 2:
                        showLoading.setTitle("已连接到服务器...");
                        break;
                    case 3:
                        prg = parseInt(
                            (parseFloat(task.downloadedSize) /
                                parseFloat(task.totalSize)) *
                            100
                        );
                        showLoading.setTitle("  正在下载,已完成：" + prg + "%  ");
                        break;
                    case 4:
                        showLoading.setTitle("正在安装...");
                        //下载完成
                        break;
                }
            });
        } catch (err) {
            plus.nativeUI.closeWaiting();
            uni.showToast({
                title: '更新失败',
                mask: false,
                duration: 1500
            });
        }
    }
}

</script>

<style lang="scss" scoped>
	.content {
        width: 100%;
        height: 100%;
		padding: 0;
		display: flex;
		flex-direction: column;
		background-color: #F2F2F2;
        .list_cell {
            padding: 28rpx  28rpx 40rpx !important;
        }
        .textarea {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 28rpx;
            color: #000000;
        }
	}
    .img {
        width: 123rpx;
        height: 123rpx;
        margin-right: 20rpx;
    }
    .right-box {
        height: 123rpx;
        padding: 12rpx 0 11rpx;
        box-sizing: border-box;
    }
    .title {
        color: $enjoy-color-title;
        font-weight: 500;
        font-size: 36rpx;
    }
    .time {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 24rpx;
        color: #888888;
    }
    .fixed_bottom {
        position: fixed;
        bottom: 0;
        left: 0;
        height: 250rpx;
        width: 100%;
    }
    .bottom-box {
        display: flex;
        height: 100rpx;
        padding: 10rpx;
        box-sizing: border-box;
        background: #FFFFFF;
        .login-btn {
            height: 80rpx;
            line-height: 80rpx;
            padding-top: 0;
            font-size: 30rpx;
        }
    }
    .notice-bar-row {
        margin: 20rpx;
        height: 110rpx;
        border-radius: 20rpx;
        overflow: hidden;
        .notification-box {
            padding-top: 16rpx;
            padding-bottom: 16rpx;
            height: 110rpx;
            border-radius: 20rpx;
            ::v-deep .uni-noticebar-icon {
                margin-right: 16rpx;
            }
            ::v-deep .uni-noticebar__content-wrapper {
                height: 78rpx !important;
                line-height: 1;
            }
            ::v-deep .uni-noticebar__content-text {
                font-size: 26rpx !important;
                line-height: 39rpx !important;
                span {
                    line-height: 39rpx;
                }
            }
        }
    }
</style>